package com.nbwyctf.helper.service;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.nbwyctf.helper.pojo.User;
import com.nbwyctf.helper.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chetaifu
 */
@Service
public class InfoService {
    private final static Logger logger = LoggerFactory.getLogger(InfoService.class);

    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Value("${thirdParty.userSpecial.token}")
    private String token;
    @Value("${thirdParty.userSpecial.tokenUrl}")
    private String tokenUrl;
    @Value("${thirdParty.userSpecial.infoUrl}")
    private String infoUrl;
    @Value("${nbwyctf.clientId}")
    private String clientId;
    @Value("${nbwyctf.clientSecret}")
    private String clientSecret;

    private static Map<String, String> infoCache = new HashMap<>();

    public static final String INFO_KEY = "info";

    @PostConstruct
    public void initData(){
        logger.info("initializing info cache infos...");
        generateInfoCache();
    }

    private void generateInfoCache() {
        try {
            String info = getInfoListStringFromApi();
            if(!Strings.isNullOrEmpty(info)){
                infoCache.put(INFO_KEY, info);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<User> getUserList() {
        String userInfo = getInfoListString();
        if (Strings.isNullOrEmpty(userInfo)) {return new ArrayList<>();}
        return JSONArray.parseArray(userInfo, User.class);
    }

    private String getInfoListString() {
        String s = infoCache.get(INFO_KEY);
        if (!Strings.isNullOrEmpty(s)) {
            return s;
        }
        generateInfoCache();
        return infoCache.get(INFO_KEY);
    }

    public String getInfoListStringFromApi() throws IOException {
        String info = null;
        // 获取token
        Map<String, Object> params = new HashMap<>();
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        String paramsString = OBJECT_MAPPER.writeValueAsString(params);
        String result = HttpUtil.postJson(tokenUrl, paramsString);
        if (null != result) {
            JsonNode tokenResult = new ObjectMapper().readTree(result);
            JsonNode data = tokenResult.get("data");
            JsonNode accessToken = data.get("access_token");
            // 重新请求
            if (accessToken != null) {
                // toString方法返回双引号，采用asText方法获取
                String token = accessToken.asText();
                logger.info("获取外包员工信息的Token：" + token);
                params = new HashMap<>();
                params.put("client_id", clientId);
                params.put("access_token", token);
                paramsString = OBJECT_MAPPER.writeValueAsString(params);
                result = HttpUtil.postJson(infoUrl, paramsString);
                JsonNode jsonResult = new ObjectMapper().readTree(result);
                JsonNode jsonData = jsonResult.get("data");
                JsonNode jsonCode = jsonResult.get("code");
                // 若接口未正常返回数据, 则直接返回空
                if (jsonCode.asInt() != 0) {
                    logger.info("信息获取失败！");
                    return null;
                }
                // 解析结果
                info = jsonData.toString();
            }
        }
        return info;
    }
}
